package com.chery.media.library.picture

import android.app.Activity
import android.content.Context
import android.content.pm.ActivityInfo
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.net.Uri
import android.widget.ImageView
import androidx.fragment.app.Fragment
import coil.imageLoader
import coil.load
import coil.request.ImageRequest
import coil.request.SuccessResult
import com.blankj.utilcode.util.LogUtils
import com.chery.media.library.R
import com.chery.media.library.contacts.PathContacts
import com.chery.media.library.extend.toColorInt
import com.luck.picture.lib.basic.PictureSelectionCameraModel
import com.luck.picture.lib.basic.PictureSelectionModel
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.config.PictureSelectionConfig.selectorStyle
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.engine.CompressFileEngine
import com.luck.picture.lib.engine.CropFileEngine
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnKeyValueResultCallbackListener
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.style.SelectMainStyle
import com.luck.picture.lib.style.TitleBarStyle
import com.luck.picture.lib.utils.ActivityCompatHelper
import com.luck.picture.lib.utils.DateUtils
import com.luck.picture.lib.utils.StyleUtils
import com.yalantis.ucrop.UCrop
import com.yalantis.ucrop.UCropImageEngine
import top.zibin.luban.Luban
import top.zibin.luban.OnNewCompressListener
import java.io.File

/**
 * @author 迈哈哈
 * @ClassName: PictureSelectHelper
 * @Description: 选择图片
 * @date 2020/11/7
 */

object PictureSelectHelper {

    val file: File by lazy { PathContacts.createFileDir(PathContacts.IMG_COMPRESS) }

    /**
     * 从相册选择
     */
    fun fromDCIM(
        activity: Activity,
        isCrop: Boolean = false,
        ratio: Pair<Float, Float> = Pair(1f, 1f),
        isSingle: Boolean = false,
        localMedias: MutableList<LocalMedia> = mutableListOf(),
        type: Int = 1,
        maxNum: Int = 9,
        apply: (PictureSelectionModel.() -> Unit)? = null,
        listener: OnResultCallbackListener<LocalMedia>? = null
    ) {
        PictureSelector.create(activity)
            .openGallery(if (type == 0) SelectMimeType.ofAll() else if (type == 1) SelectMimeType.ofImage() else SelectMimeType.ofVideo())
            .setImageEngine(CoilEngine())
            .setSelectorUIStyle(PictureSelectionConfig.pictureSelectorUIStyle)
            .isDisplayCamera(false)// 是否显示拍照按钮
            .setSelectionMode(if (isCrop || isSingle) SelectModeConfig.SINGLE else SelectModeConfig.MULTIPLE)// 多选 PictureConfig.MULTIPLE or 单选 PictureConfig.SINGLE
            .setMaxSelectNum(if (isCrop) 1 else maxNum)
            .isPreviewImage(true)// 是否可预览图片
            .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)// 设置相册Activity方向，不设置默认使用系统
            .setImageSpanCount(4)
            .setSelectedData(localMedias)
            .setCropEngine(if (isCrop) ImageFileCropEngine(ratio) else null)
            .setCompressEngine(ImageFileCompressEngine())
            .isOriginalControl(true)//开启原图选项
            .isGif(false)// 是否显示gif图片
            .isOpenClickSound(false)// 是否开启点击声音
            .isMaxSelectEnabledMask(true) // 显示蒙层
            .let {
                if (apply != null) it.apply(apply)
                if (listener == null) it.forResult(PictureConfig.CHOOSE_REQUEST)
                else it.forResult(listener)
            }
    }

    /**
     * 拍照
     */
    fun fromCamera(
        activity: Activity? = null,
        isCrop: Boolean = true,
        ratio: Pair<Float, Float> = Pair(1f, 1f),
        isVideo: Boolean = false,
        apply: (PictureSelectionCameraModel.() -> Unit)? = null,
        listener: OnResultCallbackListener<LocalMedia>? = null
    ) {
        PictureSelector.create(activity)
            .openCamera(if (isVideo) SelectMimeType.ofVideo() else SelectMimeType.ofImage())
            .setCropEngine(if (isCrop) ImageFileCropEngine(ratio) else null)
            .setCompressEngine(ImageFileCompressEngine())
            .let {
                if (apply != null) it.apply(apply)
                if (listener == null) it.forResultActivity(PictureConfig.REQUEST_CAMERA)
                else it.forResultActivity(listener)
            }
    }


    /**
     *  选择预览
     */
    fun selectPreview(
        activity: Activity,
        currentPosition: Int,
        selectedDatas: List<LocalMedia> = emptyList()
    ) {
        PictureSelector.create(activity)
            .openPreview()
            .setSelectorUIStyle(PictureSelectionConfig.pictureSelectorUIStyle)
            .setImageEngine(CoilEngine())
            .setVideoPlayerEngine(null)
            .isAutoVideoPlay(true)
            .startActivityPreview(
                currentPosition, false,
                selectedDatas as ArrayList<LocalMedia>
            )
    }

    /**
     *  图片裁减
     */
    private class ImageFileCropEngine(var ratio: Pair<Float, Float> = Pair(1f, 1f)) :
        CropFileEngine {
        override fun onStartCrop(
            fragment: Fragment,
            srcUri: Uri?,
            destinationUri: Uri?,
            dataSource: java.util.ArrayList<String?>?,
            requestCode: Int
        ) {
            val options = buildOptions(ratio)
            val uCrop = UCrop.of(srcUri!!, destinationUri!!, dataSource)
            uCrop.withOptions(options)
            uCrop.setImageEngine(object : UCropImageEngine {
                override fun loadImage(context: Context, url: String, imageView: ImageView) {
                    if (!ActivityCompatHelper.assertValidRequest(context)) {
                        return
                    }
                    imageView.load(url)
                }

                override fun loadImage(
                    context: Context,
                    url: Uri,
                    maxWidth: Int,
                    maxHeight: Int,
                    call: UCropImageEngine.OnCallbackListener<Bitmap>
                ) {
                    val target = ImageRequest.Builder(context)
                        .data(url)
                        .size(maxWidth, maxHeight)
                        .build()
                    call.onCall((((context.imageLoader.enqueue(target) as SuccessResult).drawable) as BitmapDrawable).bitmap)
                }
            })
            uCrop.start(fragment.requireActivity(), fragment, requestCode)
        }
    }

    /**
     * 配制UCrop，可根据需求自我扩展
     *
     * @return
     */
    private fun buildOptions(ratio: Pair<Float, Float>?): UCrop.Options {
        val options = UCrop.Options().apply {
            setHideBottomControls(true)
            setFreeStyleCropEnabled(true)
            setShowCropFrame(true)
            setShowCropGrid(true)
            setCircleDimmedLayer(false)
            if (ratio != null)
                withAspectRatio(ratio.first, ratio.second)
            isCropDragSmoothToCenter(false)
            isForbidCropGifWebp(true)
            isForbidSkipMultipleCrop(false)
            setMaxScaleMultiplier(100f)

            if (selectorStyle != null && selectorStyle.selectMainStyle.statusBarColor != 0
            ) {
                val mainStyle: SelectMainStyle = selectorStyle.selectMainStyle
                val isDarkStatusBarBlack = mainStyle.isDarkStatusBarBlack
                val statusBarColor = mainStyle.statusBarColor
                isDarkStatusBarBlack(isDarkStatusBarBlack)
                if (StyleUtils.checkStyleValidity(statusBarColor)) {
                    setStatusBarColor(statusBarColor)
                    setToolbarColor(statusBarColor)
                } else {
                    setStatusBarColor(R.color.ps_color_grey.toColorInt())
                    setToolbarColor(R.color.ps_color_grey.toColorInt())
                }
                val titleBarStyle: TitleBarStyle = selectorStyle.titleBarStyle
                if (StyleUtils.checkStyleValidity(titleBarStyle.titleTextColor)) {
                    setToolbarWidgetColor(titleBarStyle.titleTextColor)
                } else {
                    setToolbarWidgetColor(R.color.ps_color_white.toColorInt())
                }
            } else {
                setStatusBarColor(R.color.ps_color_grey.toColorInt())
                setToolbarColor(R.color.ps_color_grey.toColorInt())
                setToolbarWidgetColor(R.color.ps_color_white.toColorInt())
            }
        }
        return options
    }

    /**
     *  图片压缩引擎
     */
    private class ImageFileCompressEngine : CompressFileEngine {
        override fun onStartCompress(
            context: Context,
            source: ArrayList<Uri>,
            call: OnKeyValueResultCallbackListener
        ) {
            Luban.with(context).load(source).ignoreBy(100).setRenameListener { filePath ->
                val indexOf = filePath.lastIndexOf(".")
                val postfix = if (indexOf != -1) filePath.substring(indexOf) else ".jpg"
                DateUtils.getCreateFileName("CMP_") + postfix
            }.setCompressListener(object : OnNewCompressListener {
                override fun onStart() {}
                override fun onSuccess(source: String, compressFile: File) {
                    call.onCallback(source, compressFile.absolutePath)
                }

                override fun onError(source: String, e: Throwable) {
                    LogUtils.e("图片压缩出错${e.message}")
                    call.onCallback(source, null)
                }
            }).launch()
        }
    }


}


